var API=(function(){
    const BASE_URL='https://study.duyiedu.com';
    const TOKEN_KEY='token';
    function get(url){
        const token=localStorage.getItem(TOKEN_KEY);
        const headers={}
        if(token){
            headers.authorization='Bearer'+' '+token;
        }
        return  fetch(BASE_URL+url,{headers});
    }
    function post(url,bodyObj){
        const token=localStorage.getItem(TOKEN_KEY);
        const headers={
            'Content-Type':'application/json',
        }
        if(token){
            headers.authorization='Bearer'+' '+token;
        }
        return  fetch(BASE_URL+url,{
            method:'POST',
            headers,
            body:JSON.stringify(bodyObj)});
    }
    async function reg(userInfo){
        const resp= await post('/api/user/reg',userInfo)
        return await resp.json();
    }
    async function login(loginInfo){
        const resp= await post('/api/user/login',loginInfo)
        const result=await resp.json();
       if(result.code===0){
        const token=resp.headers.get('Authorization');
        localStorage.setItem(TOKEN_KEY,token);
       }
       return result;
    }
    async function exists(loginId){
        const resp= await get(`/api/user/exists?loginId=${loginId}`)
        return await resp.json();
    }
    async function profile(){
        const resp=await get('/api/user/profile');
        return await resp.json();
    }
    async function sendChat(content){
        const resp=await post('/api/chat',{
            content
        });
        return await resp.json();
    }
    async function getHistory(){
        const resp=await get('/api/chat/history');
        return await resp.json();
    }
    function loginOut(){
        localStorage.removeItem(TOKEN_KEY)
    }
    // reg({loginId:'leodada1212',nickname:'leo',loginPwd:'123456'}).then((data)=>{
    //     console.log(data);
    // })
    // console.log(exists('leodada1212'));
    return {
        reg,
        login,
        exists,
        profile,
        sendChat,
        getHistory,
        loginOut
    }
})()
